package com.zkx.laolaiyi.aspect;

import com.zkx.laolaiyi.annotation.AutoFill;
import com.zkx.laolaiyi.constant.AutoFillConstants;
import com.zkx.laolaiyi.constant.ExceptionMsgConstant;
import com.zkx.laolaiyi.constant.ResultCodeConstant;
import com.zkx.laolaiyi.constant.ResultMsgConstant;
import com.zkx.laolaiyi.entity.LoginAdmin;
import com.zkx.laolaiyi.entity.LoginUser;
import com.zkx.laolaiyi.enumeration.DBOperationType;
import com.zkx.laolaiyi.exceptions.UnknownException;
import com.zkx.laolaiyi.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    /**
     * 匹配mapper或是service包下的所有类的所有方法，并且方法被@interface AutoFill修饰
     */
    @Pointcut(
            "(execution(* com.zkx.laolaiyi.service.*.*(..)) || execution(* com.zkx.laolaiyi.mapper.*.*(..))) && @annotation(com.zkx.laolaiyi.annotation.AutoFill)"
    )
    public void autoFillPointcut() {

    }

    @Before("autoFillPointcut()")
    public void autoFill(JoinPoint joinPoint) {
        try {
            // 获取被注解修饰的方法的签名
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取参数对象
            Object target = joinPoint.getArgs()[0];
            // 获取注解的数据库操作类型
            DBOperationType operationType = signature.getMethod().getAnnotation(AutoFill.class).value();
            // 获取target的原始类型
            Class<?> sourceClass = target.getClass();
            // 获取原始类型中的set方法
            Method setCreateTime = sourceClass.getDeclaredMethod(AutoFillConstants.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = sourceClass.getDeclaredMethod(AutoFillConstants.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateUser = sourceClass.getDeclaredMethod(AutoFillConstants.SET_CREATE_USER, Long.class);
            Method setUpdateUser = sourceClass.getDeclaredMethod(AutoFillConstants.SET_UPDATE_USER, Long.class);
            LocalDateTime now = LocalDateTime.now();
            // 执行set方法
            if (operationType == DBOperationType.INSERT) {
                // 获取当前用户
                Object currentRole = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                setCreateTime.invoke(target, now);
                setUpdateTime.invoke(target, now);
                if (currentRole instanceof LoginUser currentUser) {
                    setCreateUser.invoke(target, currentUser.getUid());
                    setUpdateUser.invoke(target, currentUser.getUid());
                } else if (currentRole instanceof LoginAdmin currentAdmin) {
                    setCreateUser.invoke(target, currentAdmin.getUserId());
                    setUpdateUser.invoke(target, currentAdmin.getUserId());
                }
            } else if (operationType == DBOperationType.UPDATE) {
                // 获取当前用户
                Object currentRole = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                setUpdateTime.invoke(target, now);
                if (currentRole instanceof LoginUser currentUser) {
                    setUpdateUser.invoke(target, currentUser.getUid());
                } else if (currentRole instanceof LoginAdmin currentAdmin) {
                    setUpdateUser.invoke(target, currentAdmin.getUserId());
                }
            } else if (operationType == DBOperationType.LOGIN_INSERT) {
                setCreateTime.invoke(target, now);
                setUpdateTime.invoke(target, now);
            }
        } catch (Throwable e) {
            log.error("自动插入公共字段时发生未知异常：{}", e.getMessage());
            throw new UnknownException(ExceptionMsgConstant.UNKNOWN_EXCEPTION);
        }
    }
}
